<template>
    <div style="border:3px solid #000;">
        <p>AES的JavaScript代码与Java代码同步加密测试</p>
        <input id="data" type="text" placeholder="测试需要加密的data" v-model="msg" />
        <button @click="aes_test">加密</button><br />
        服务端的加密结果
        <p>{{ serverResult }}</p>
        <br />
        客户端的加密结果
        <p>{{ clientResult }}</p>
        <br />
        服务端的加密结果是否等于客户端的加密结果：
        <p style="color: red">{{ booleanResult }}</p>
    </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue'
import CryptoJS from 'crypto-js'
import $ from 'jquery';

const msg = ref('');
const booleanResult = ref('');
const serverResult = ref('');
const clientResult = ref('');

const aes_test = () => {
    console.log("要加密的数据", msg.value);
    const myData = msg.value;
    if (myData === "") {
        booleanResult.value = "加密失败，请输入数据";
    } else {
        const data_clientAES = aes_client(myData);
        aes_server(myData);
        if (data_clientAES === serverResult.value) {
            booleanResult.value = "同步加密成功";
        } else {
            booleanResult.value = "同步加密失败";
        }
    }
}

const aes_client = (data: string) => {
    const key = CryptoJS.enc.Latin1.parse("abcdef0123456789");
    const iv = CryptoJS.enc.Latin1.parse("0123456789abcdef");
    const encrypted = CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding,
    });
    clientResult.value = encrypted.toString();
    return encrypted.toString();
}

const aes_server = (data: string) => {
    const settings = {
        url: "http://localhost:8086/encrypt/aes_encrypt",
        method: "POST",
        timeout: 0,
        async: false,
        headers: {
          "Content-Type": "text/plain",
        },
        data: data,
      };

      $.ajax(settings).done(function (response: { data: string; }) {
        serverResult.value = response.data;
      });
}
</script>
<style scoped></style>